package com.leyou.auth.task;


import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableConfigurationProperties(JwtProperties.class)
@Slf4j
public class GetTokenInTime {



    @Autowired
    private JwtProperties props;

    @Autowired
    private AuthService authService;


    private String token;

    final long intervalTime = 86400000L;

    @Scheduled(fixedDelay = intervalTime) //第一次调用是启动时候
    public void getTokenFromAuth() {

        while (true) {
            try {
                this.token = authService.authorize(props.getApp().getId(), props.getApp().getSecret());
                log.info("【授权中心】获取token成功");
                break;
            } catch (Exception e) {
                log.error("【授权中心】获取token失败");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public String getToken() {
        return token;
    }
}
